<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use JWTAuth;
use JWTFactory;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Claims\Factory;
use Illuminate\Http\Request;

use App\Http\Models\Auth\UserModel;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';
    protected $user_model;
    public $user;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
        $this->user_model = new UserModel();
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    public function getLogin()
    {
        return view('auth.login');
    }

    //validate the request, to parse $user model from parm $token
    private function validateAuth(Request $request)
    {
        $token = $request->get('token','');
        $authed = false;
        if($token)
        {
            $payload = JWTAuth::parseToken()->getPayload();
            $claim = $payload->toArray();
            $user = array(
                'email' => $claim['email'],
                'password' => $claim['password']
            );
            $authed = $this->checkUser($user);
            if($authed)
            {
                $this->user = $user;
            }
        }
        return $authed;
    }

    //check the user login;
    public function postLogin(Request $request)
    {
        $email = $request->get('email','');
        $password = $request->get('password','');

        $user = array(
            'email' => $email,
            'password' => md5($password)
        );
        $check = $this->checkUser($user);
        $token = '';
        if($check)
        {
            $token = $this->getToken($user);
        }
        return view('auth.check')
            ->with('token', $token);
    }


    //to test the parm token from client
    public function showTest(Request $request)
    {
        $authed = $this->validateAuth($request);
        return view('auth.test')
            ->with('authed', $authed)
            ->with('user', $this->user);

    }


    public function checkUser($user)
    {
        $check = 0;
        $user_count = $this->user_model->countWhere($user);
        if($user_count > 0)
        {
            $check = 1;
        }
        return $check;
    }

    public function getToken($user)
    {
        $token = '';
        if(count($user))
        {
            $payload = JWTFactory::make($user);
            $token = JWTAuth::encode($payload);
        }
        return $token;
    }

    public function authenticatea(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // all good so return the token
        return response()->json(compact('token'));
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
